package com.yboot.starter.common.core.web.advice;

import com.yboot.starter.common.core.exception.BusinessException;
import com.yboot.starter.common.core.web.vo.ParameterValidMessageVo;
import com.yboot.starter.common.core.web.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;

@Order(70)
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result handleException(HttpServletRequest req, HttpServletResponse response, MethodArgumentNotValidException e) {
        log.error("[{}] {}", req.getMethod(), req.getRequestURI(), e);
        String errorMsg = e.getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(","));
        List<ParameterValidMessageVo> vos = e.getAllErrors().stream().map(i -> (FieldError) i)
                                 .map(j -> new ParameterValidMessageVo(j.getField(), j.getDefaultMessage()))
                                 .collect(Collectors.toList());
        exceptionHandler(req.getRequestURI(), errorMsg);

        // 处理异常，例如记录日志等
        return Result.error("参数缺失", vos);
    }

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Result handleException(HttpServletRequest req, HttpServletResponse response, BindException e) {
        log.error("[{}] {}", req.getMethod(), req.getRequestURI(), e);
        String errorMsg = e.getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(","));
        List<ParameterValidMessageVo> vos = e.getAllErrors().stream().map(i -> (FieldError) i)
                .map(j -> new ParameterValidMessageVo(j.getField(), j.getDefaultMessage()))
                .collect(Collectors.toList());
        exceptionHandler(req.getRequestURI(), errorMsg);
        // 处理异常，例如记录日志等
        return Result.error("参数类型不匹配", vos);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public Result handleException(HttpServletRequest req, HttpServletResponse response, ConstraintViolationException e) {
        log.error("[{}] {}", req.getMethod(), req.getRequestURI(), e);
        exceptionHandler(req.getRequestURI(), e.getMessage());
        // 处理异常，例如记录日志等
        return Result.error("校验参数约束失败", e.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Result handleException(HttpServletRequest req, HttpServletResponse response, RuntimeException e) {
        log.error("[{}] {}", req.getMethod(), req.getRequestURI(), e);
        exceptionHandler(req.getRequestURI(), e.getMessage());
        // 处理异常，例如记录日志等
        return Result.error("服务器内部错误:" + e.getMessage());
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public Result handleException(HttpServletRequest req, HttpServletResponse response, BusinessException e) {
        log.error("[{}] {}", req.getMethod(), req.getRequestURI(), e);
        exceptionHandler(req.getRequestURI(), e.getMessage());
        // 处理异常，例如记录日志等
        return Result.error(e.getMessage());
    }

    private static void exceptionHandler(String uri, String errorMsg) {
        log.error("===GlobalExceptionHandler start===\n uri: {}\n msg: {} \n ===GlobalExceptionHandler end===",
                 new Object[]{uri, errorMsg});
    }

}